<template>
  <div>
    <!--信息值-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card leab_top">
      <!--信息值-->
      <div>
        <el-row>
          <el-button type="primary" @click="addlei()">添加分类</el-button>
        </el-row>
        <!--表格-->
        <el-row class="leab_top">
          <!--分类名称-->
          <tree-table
            :data="gories"
            index-text="#"
            show-index
            :expand-type="false"
            :selection-type="false"
            :border="true"
            :columns="columns"
          >
            <!--是否有效-->
            <template slot="solet0" slot-scope="scope">
              <i v-if="scope.row.cat_deleted==false" class="el-icon-success"></i>
              <!-- 错误的类名-->
              <i v-else class="el-icon-err"></i>
            </template>
            <!--排序-->
            <template slot="solet1" slot-scope="scope">
              <el-button type="primary" size="mini" v-if="scope.row.cat_level=='0'" plain>一级</el-button>
              <el-button type="warning" size="mini" v-else-if="scope.row.cat_level=='1'" plain>二级</el-button>
              <el-button type="danger" size="mini" plain v-else>三级</el-button>
            </template>
            <!--操作-->
            <template slot="solet2" slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="caegories(scope.row)"
                size="small"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="caegoDele(scope.row)"
              >删除</el-button>
            </template>
          </tree-table>
        </el-row>
        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[3, 5, 8, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!--添加分类框-->
    <el-dialog title="添加分类" :visible.sync="dialogVisible" width="50%" @close="cleartL()">
      <el-form
        :model="querydata"
        :rules="handquery"
        ref="ruled"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="querydata.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!--model：每次选择存储的值：是个数组,在prop设置
             options：选择框的循环内容，不然会报错，官网没有
          :props: 规则，必须设置-->
          <el-cascader
            class="casc"
            v-model="cascval"
            :options="tions"
            :props="pros"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addqueRen()">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑分类框-->
    <el-dialog title="编辑" :visible.sync="UpdeVisible" width="50%" @close="cleartL()">
      <el-form
        :model="querydata"
        :rules="handquery"
        ref="ruled"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="querydata.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="UpdeVisible = false">取 消</el-button>
        <el-button type="primary" @click="Updet()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//引入删除的函数
import dele from "../delet.js";
//请求当前数据
export default {
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.initgories();
  },
  data() {
    return {
      //当前页存储数据
      gories: [],
      //指定请求的数据条数
      queryInfo: {
        type: 3,
        pagenum: 1, //当前页
        pagesize: 5 //显示几条数据
      },
      //数值总条数
      total: 0,
      //列的数据
      columns: [
        {
          label: "分类名称", //当前表格的标题
          prop: "cat_name" //当列显示的数据属性
        },
        {
          label: "是否有效", //创建下一列
          type: "template",
          template: "solet0" //插槽（名字）该组件多次循环只能签套模板
        },
        {
          label: "排序", //创建下一列
          type: "template",
          template: "solet1" //插槽（名字）该组件多次循环只能签套模板
        },
        {
          label: "操作", //创建下一列
          type: "template",
          template: "solet2" //插槽（名字）该组件多次循环只能签套模板
        }
      ],
      //类框显示与隐藏
      dialogVisible: false,
      //分类数据
      querydata: {
        cat_name: "", //分类名称
        cat_pid: 0, //父类名称id
        cat_level: 0 //分类层级0
      },
      //分类数据验证
      handquery: {
        //分类名称验证
        cat_name: [
          { required: true, message: "请输入类名称" },
          { min: 3, message: "请输入最少3个长度", trigger: "blur" }
        ]
      },
      //级联选择器存储的值
      cascval: [],
      //级联选择器显示的数据
      tions: [],
      //级联选择器控制数据
      pros: {
        expandTrigger: "hover",
        checkStrictly: "true",
        value: "cat_id", //每次上交的值
        label: "cat_name", //级联的数据
        children: "children" //下一级的属性
      },
      //用户编辑框
      UpdeVisible: false,
      //编辑的名字
      UpdeVal: "",
      //编辑用户时需要的id
      bid: ""
    };
  },
  methods: {
    //初始化函数
    async initgories() {
      let { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status != 200) {
        return this.$message.error("请求失败");
      }
      this.gories = res.data.result;
      this.total = res.data.total;
      /*console.log(this.total);
      console.log(this.gories);*/
    },
    //当前页的数据条数改变时
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.initgories();
    },
    //当前页数改变时
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.initgories();
    },
    //添加分类
    async addlei() {
      let { data: res } = await this.$http.get("categories", {
        params: { type: "2" }
      });
      if (res.meta.status != 200) {
        return this.$message.error("请求错误");
      }
      //渲染数据
      this.tions = res.data;
      // console.log(res.data);
      this.dialogVisible = true;
    },
    //确认添加类
    addqueRen() {
      this.$refs.ruled.validate(async item => {
        if (item) {
          let { data: res } = await this.$http.post(
            "categories",
            this.querydata
          );
          if (res.meta.status != 201) {
            console.log(res.meta);
            return this.$message.error("失败");
          }
          //初始化
          this.$message.success("成功");
          //初始化
          this.initgories();
          //关闭弹框
          this.dialogVisible = false;
        } else {
          return this.$message.error("请输入用户信息");
        }
      });
    },
    //清空分类数据
    cleartL() {
      this.$refs.ruled.resetFields();
      this.cascval = [];
      this.querydata = {
        cat_name: "", //分类名称
        cat_pid: 0, //父类名称id
        cat_level: 0 //分类层级
      };
    },
    //选中级联选择器变化的数据
    handleChange() {
      //表示选中了
      if (this.cascval.length > 0) {
        this.querydata.cat_pid = this.cascval[this.cascval.length - 1];
      }
      this.querydata.cat_level = this.cascval.length;
      //console.log(this.querydata);
    },
    //产品编辑
    caegories(content) {
      console.log(content);
      //
      this.bid = content.cat_id;
      this.UpdeVisible = true;
    },
    //产品编辑修改
    async Updet() {
      //判断用户是否有输入改值
      if (!this.querydata.cat_name.trim().length) {
        return this.$message.error("请输入文本值");
      }
       //有，发送ajax请求
      let { data: res } = await this.$http.put(`categories/${this.bid}`, {
        cat_name:this.querydata.cat_name
      });
      if(res.meta.status!=200){
        return this.$message.error('编辑失败');
      }
      //成功，响应成功
      this.$message.success('编辑成功');
      //提示对话框，
      this.UpdeVisible = false;
      //更新当前用户
      this.initgories();
    },
    //产品删除(仍然有bug)
    async caegoDele(content) {
      let a = await dele.dele(this.$confirm);
      if (a != "confirm") {
        return this.$message("取消删除");
      }
      //删除数组
      this.prty(content.cat_id, this.gories);
      //放松aja下删除
      let { data: res } = await this.$http.delete(
        `categories/${content.cat_id}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除分类成功");
     


    },
    //递归查找删除
    prty(bid, target) {
       target.forEach((item, index) => {
        if (item.cat_id == bid) {
          target.splice(index, 1);
          return;
        } else {
          if (item.children) {
            this.prty(bid, item.children);
          }
        }
      });
    }
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {}
};
</script>
<style scoped lang='less'>
.leab_top {
  margin: 15px 0;
}
.el-icon-success {
  color: greenyellow;
}
.casc {
  width: 100%;
}

/* @import url(); 引入css类 */
</style>